// const { query } = require('express')
const exp =require('express')
// const formidable=require('formidable')
const taskMo =require('./db/modul/taskModul')
// const {resolve}=require('path')
// function Cour(req, res, next) {
//   res.setHeader('Access-Control-Allow-Origin', '*'); // 允许跨域请求 任意
//   res.setHeader('Access-Control-Allow-Headers', "*"); // 允许客户端可以设置请求头  
//   res.setHeader('Access-Control-Allow-Methods', "*"); // 允许各种请求方式进行任意跨域请求
//   res.setHeader('Access-Control-Expose-Headers', "*"); //暴露响应头信息
//   next()
// }


let app=exp()
// app.use(Cour)
app.use(exp.urlencoded({extends:false}))
app.use(exp.json())
app.use(exp.static(__dirname+'/public'))

// let readFile=formidable({
//   uploadDir:resolve(__dirname,'./public/userFile'),
//   keepExtensions:true,
//   maxFieldsSize:1024*1024
// })

//获取数据
app.get('/todos',async(req,res)=>{
  // res.redirect('/')
  
  try {
    let data=await taskMo.find()
  // console.log(data);
  res.json({
    code:2000,
    data,
    message:'获取成功'
  })
  } catch (error) {
    
  }
  
})
//添加数据
app.post('/todos',async(req,res)=>{
  let {title}=req.body
  try {
     let data=await taskMo.create({
    title,
    done:false
  })
  res.json({
    code:2000,
    data,
    message:'添加成功'
  })
  } catch (error) {
    res.json({
      code:2001,
      message:'抱歉,添加失败'
    })
  }
 
})
//更新数据
app.post('/dos',async(req,res)=>{
  
  let {id,done}=req.body
  let data=await taskMo.updateOne({_id:id},{done})
  // console.log(data);
  res.json({
    code:2000,
    data,
    message:'更新状态成功'
  })
})
//删除数据
app.delete('/todos',async(req,res)=>{
  let {id}=req.query
  try {
     let data =await taskMo.deleteOne({_id:id})
  res.json({
    code:2000,
    data,
    message:'删除成功'
  })
  } catch (error) {
    res.json({
      code:2001,
      message:'删除失败'
    })
  }
 
})
//删除所有完成的
app.post('/tododel',async(req,res)=>{
  let data=await taskMo.deleteMany({done:true})
  res.json({
    code:2000,
    data,
    message:'清除完成任务成功'
  })
})
//全部选中
app.post('/alldos',async(req,res)=>{
  let {done}=req.body
  let data=await taskMo.updateMany({done})
  res.json({
    code:2000,
    data,
    message:'更新成功'
  })
})

app.listen(3002,()=>{
  console.log('启动啦~~~~');
})